package com.softa.common.sysconfig.shiro.realm;

import com.softa.common.constant.Constants;
import com.softa.common.entity.SysLog;
import com.softa.common.entity.SysUser;
import com.softa.common.service.LogService;
import com.softa.common.service.ResourceService;
import com.softa.common.service.RoleService;
import com.softa.common.service.UserService;
import com.softa.common.sysconfig.shiro.token.KissoToken;
import com.softa.common.utils.DateUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Set;

/**
 * 
*   后台登陆认证授权
 * Created by yangl on 2017/8/6.
*
 */
public class AdminRealm extends AuthorizingRealm {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private LogService logService;

    @Resource
    private ResourceService resourceService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof KissoToken;
    }
    
    // 授权 
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String)principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        if(Constants.ADMIN.equals(username)){
            authorizationInfo.setRoles(roleService.findAllRoles());
            authorizationInfo.setStringPermissions(resourceService.findAllPermissions());
        }else{
            Set<String> roleSet=userService.findRoles(username);
            authorizationInfo.setRoles(roleSet);
            authorizationInfo.setStringPermissions(userService.findPermissions(username));
        }
        return authorizationInfo;
    }
    // 认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        String username = (String)token.getPrincipal();

        SysUser user = null;

        if(Constants.ADMIN.equals(username)){
            user = userService.findAdminUser();
        }else{
            user = userService.findByUsername(username);
        }

        if(user == null) {
            //没找到帐号
            throw new UnknownAccountException();
        }

        if(Boolean.TRUE.equals(user.getLocked())) {
            //帐号锁定
            throw new LockedAccountException();
        }

        System.out.println(getName());

        //交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
//        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
//                //用户名
//                user.getUsername(),
//                //密码
//                user.getPassword(),
//                //salt=username+salt
//                ByteSource.Util.bytes(user.getUsername() + user.getSalt()),
//                //realm name
//                getName()
//        );
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, username, "my_realm");

        /**日志记录 */
        SysLog log = new SysLog();
		log.setOpertype("登录");
		String createip= null;
		try {
			InetAddress host = InetAddress.getLocalHost();
			createip = host.getHostAddress();
			log.setContent(username+"登录");
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		log.setCreateip(createip);
		log.setCreatetime(DateUtils.getyyyyMMddHHmmsssplit(new Date()));
		log.setType(1);
		logService.saveLog(log);
		
        return authenticationInfo;
    }

    @Override
    public void clearCachedAuthorizationInfo(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
    }

    @Override
    public void clearCachedAuthenticationInfo(PrincipalCollection principals) {
        super.clearCachedAuthenticationInfo(principals);
    }

    @Override
    public void clearCache(PrincipalCollection principals) {
        super.clearCache(principals);
    }

    public void clearAllCachedAuthorizationInfo() {
        getAuthorizationCache().clear();
    }

    public void clearAllCachedAuthenticationInfo() {
        getAuthenticationCache().clear();
    }

    public void clearAllCache() {
        clearAllCachedAuthenticationInfo();
        clearAllCachedAuthorizationInfo();
    }

}
